<?php
// 设置响应头
header('Content-Type: application/json; charset=utf-8');

// 获取请求参数
$action = isset($_GET['action']) ? $_GET['action'] : '';
$version = isset($_GET['version']) ? $_GET['version'] : '';
$departure = isset($_GET['departure']) ? $_GET['departure'] : '';
$destination = isset($_GET['destination']) ? $_GET['destination'] : '';
$weekdays = isset($_GET['weekdays']) ? explode(',', $_GET['weekdays']) : ['1','2','3','4','5','6','7']; // 默认全选

// 航空公司IATA代码映射
$airlines = [
    'HU' => '海南航空',
    'CN' => '大新华航空',
    'JD' => '首都航空',
    'GS' => '天津航空',
    '8L' => '祥鹏航空',
    'PN' => '西部航空',
    'GX' => '北部湾航空',
    'UQ' => '乌鲁木齐航空',
    'FU' => '福州航空',
    '9H' => '长安航空',
    'Y8' => '金鹏航空',
    'JV' => '金鹿公务机'
];

// 读取航班数据
function loadFlightData($version) {
    // 根据版本选择对应的数据文件
    $jsonFile = '';
    switch ($version) {
        case '666_summer':
        case '2666_summer':
            $jsonFile = 'flight_dataxia.json';
            break;
        case '666_winter':
        case '2666_winter':
            $jsonFile = 'flight_datadong.json';
            break;
        default:
            return [];
    }
    
    if (file_exists($jsonFile)) {
        $content = file_get_contents($jsonFile);
        $flightData = json_decode($content, true);
        return $flightData;
    }
    return [];
}

// 根据航班号获取航空公司信息
function getAirlineInfo($flightNumber) {
    global $airlines;
    // 提取航班号前2个字符作为IATA代码
    $iata = substr($flightNumber, 0, 2);
    if (isset($airlines[$iata])) {
        return [
            'iata' => $iata,
            'name' => $airlines[$iata]
        ];
    }
    return [
        'iata' => 'Unknown',
        'name' => '未知航空公司'
    ];
}

// 检查星期是否匹配
function weekdayMatch($flight, $selectedWeekdays) {
    $flightWeekdays = str_split($flight['schedule']);
    $commonWeekdays = array_intersect($flightWeekdays, $selectedWeekdays);
    return !empty($commonWeekdays);
}

// 获取所有城市列表（按拼音排序）
function getAllCities($flightData) {
    $cities = [];
    foreach ($flightData as $flight) {
        if (!in_array($flight['departure_city'], $cities)) {
            $cities[] = $flight['departure_city'];
        }
        if (!in_array($flight['arrival_city'], $cities)) {
            $cities[] = $flight['arrival_city'];
        }
    }
    
    // 使用PHP的排序函数，对于中文会根据编码排序
    sort($cities, SORT_LOCALE_STRING);
    return $cities;
}

// 检查产品版本是否匹配
function versionMatch($flight, $version) {
    // 根据版本类型检查对应的产品版本
    switch ($version) {
        case '666_summer':
        case '666_winter':
            return in_array('666', $flight['applicable_products']);
        case '2666_summer':
        case '2666_winter':
            return in_array('2666', $flight['applicable_products']);
        default:
            return false;
    }
}

// 搜索直达航班
function searchDirectFlights($flightData, $version, $departure, $destination, $weekdays) {
    $results = [];
    foreach ($flightData as $flight) {
        if (versionMatch($flight, $version) && weekdayMatch($flight, $weekdays)) {
            $matchDeparture = empty($departure) || $flight['departure_city'] == $departure;
            $matchDestination = empty($destination) || $flight['arrival_city'] == $destination;
            
            if ($matchDeparture && $matchDestination) {
                // 添加航空公司信息
                $flight['airline'] = getAirlineInfo($flight['flight_number']);
                $results[] = $flight;
            }
        }
    }
    return $results;
}

// 获取出发地可以到达的所有目的地航班
function getDestinationsFromCity($flightData, $version, $departure, $weekdays) {
    $flights = [];
    foreach ($flightData as $flight) {
        if (versionMatch($flight, $version) && $flight['departure_city'] == $departure && weekdayMatch($flight, $weekdays)) {
            // 添加航空公司信息
            $flight['airline'] = getAirlineInfo($flight['flight_number']);
            $flights[] = $flight;
        }
    }
    return $flights;
}

// 获取可以到达目的地的所有出发地航班
function getOriginsToCity($flightData, $version, $destination, $weekdays) {
    $flights = [];
    foreach ($flightData as $flight) {
        if (versionMatch($flight, $version) && $flight['arrival_city'] == $destination && weekdayMatch($flight, $weekdays)) {
            // 添加航空公司信息
            $flight['airline'] = getAirlineInfo($flight['flight_number']);
            $flights[] = $flight;
        }
    }
    return $flights;
}

// 规划中转路径（最多中转两次）
function planTransferRoutes($flightData, $version, $departure, $destination, $weekdays) {
    $routes = [];
    
    // 一次中转
    $oneTransferRoutes = findOneTransferRoutes($flightData, $version, $departure, $destination, $weekdays);
    foreach ($oneTransferRoutes as $route) {
        // 为每个航班添加航空公司信息
        foreach ($route as &$flight) {
            $flight['airline'] = getAirlineInfo($flight['flight_number']);
        }
        $routes[] = $route;
    }
    
    // 两次中转（如果一次中转少于5条结果）
    if (count($routes) < 5) {
        $twoTransferRoutes = findTwoTransferRoutes($flightData, $version, $departure, $destination, $weekdays);
        foreach ($twoTransferRoutes as $route) {
            // 为每个航班添加航空公司信息
            foreach ($route as &$flight) {
                $flight['airline'] = getAirlineInfo($flight['flight_number']);
            }
            
            // 避免重复路径
            $routeStr = serialize($route);
            $isDuplicate = false;
            foreach ($routes as $existingRoute) {
                if (serialize($existingRoute) == $routeStr) {
                    $isDuplicate = true;
                    break;
                }
            }
            if (!$isDuplicate) {
                $routes[] = $route;
            }
        }
    }
    
    // 限制返回结果数量
    return array_slice($routes, 0, 10);
}

// 查找一次中转路径
function findOneTransferRoutes($flightData, $version, $departure, $destination, $weekdays) {
    $routes = [];
    $fromFlights = []; // 从出发地出发的航班
    $toFlights = [];   // 到达目的地的航班
    
    // 分类航班
    foreach ($flightData as $flight) {
        if (versionMatch($flight, $version) && weekdayMatch($flight, $weekdays)) {
            if ($flight['departure_city'] == $departure) {
                $fromFlights[] = $flight;
            }
            if ($flight['arrival_city'] == $destination) {
                $toFlights[] = $flight;
            }
        }
    }
    
    // 寻找中转点
    foreach ($fromFlights as $fromFlight) {
        foreach ($toFlights as $toFlight) {
            if ($fromFlight['arrival_city'] == $toFlight['departure_city']) {
                // 检查是否有共同的运营日
                $commonDays = array_intersect(str_split($fromFlight['schedule']), str_split($toFlight['schedule']));
                if (!empty($commonDays)) {
                    // 进一步检查是否满足选中的星期
                    $commonWithSelected = array_intersect($commonDays, $weekdays);
                    if (!empty($commonWithSelected)) {
                        $routes[] = [$fromFlight, $toFlight];
                    }
                }
            }
        }
    }
    
    return $routes;
}

// 查找两次中转路径
function findTwoTransferRoutes($flightData, $version, $departure, $destination, $weekdays) {
    $routes = [];
    
    // 先找到所有从出发地到中间点的航班
    $firstLegFlights = [];
    foreach ($flightData as $flight) {
        if (versionMatch($flight, $version) && $flight['departure_city'] == $departure && weekdayMatch($flight, $weekdays)) {
            $firstLegFlights[] = $flight;
        }
    }
    
    // 再找到所有中间点之间的航班
    $secondLegFlights = [];
    foreach ($flightData as $flight) {
        if (versionMatch($flight, $version) && weekdayMatch($flight, $weekdays)) {
            $secondLegFlights[] = $flight;
        }
    }
    
    // 最后找到所有从中间点到目的地的航班
    $thirdLegFlights = [];
    foreach ($flightData as $flight) {
        if (versionMatch($flight, $version) && $flight['arrival_city'] == $destination && weekdayMatch($flight, $weekdays)) {
            $thirdLegFlights[] = $flight;
        }
    }
    
    // 组合三次航班
    foreach ($firstLegFlights as $first) {
        foreach ($secondLegFlights as $second) {
            if ($first['arrival_city'] == $second['departure_city']) {
                foreach ($thirdLegFlights as $third) {
                    if ($second['arrival_city'] == $third['departure_city']) {
                        // 检查是否有共同的运营日
                        $commonDays1 = array_intersect(str_split($first['schedule']), str_split($second['schedule']));
                        $commonDays2 = array_intersect(str_split($second['schedule']), str_split($third['schedule']));
                        if (!empty($commonDays1) && !empty($commonDays2)) {
                            // 进一步检查是否满足选中的星期
                            $commonWithSelected1 = array_intersect($commonDays1, $weekdays);
                            $commonWithSelected2 = array_intersect($commonDays2, $weekdays);
                            if (!empty($commonWithSelected1) && !empty($commonWithSelected2)) {
                                $routes[] = [$first, $second, $third];
                            }
                        }
                    }
                }
            }
        }
    }
    
    return $routes;
}

// 处理不同的API请求
$flightData = loadFlightData($version);
$response = [];

switch ($action) {
    case 'getCities':
        // 返回所有城市列表
        $cities = getAllCities($flightData);
        echo json_encode($cities, JSON_UNESCAPED_UNICODE);
        break;
        
    case 'searchFlights':
        // 根据不同的查询条件返回结果
        if (!empty($departure) && !empty($destination)) {
            // 搜索直达航班
            $directFlights = searchDirectFlights($flightData, $version, $departure, $destination, $weekdays);
            $response['directFlights'] = $directFlights;
            
            // 如果没有直达航班，规划中转路径
            if (empty($directFlights)) {
                $transferRoutes = planTransferRoutes($flightData, $version, $departure, $destination, $weekdays);
                $response['transferRoutes'] = $transferRoutes;
            }
        } elseif (!empty($departure)) {
            // 只选择了出发地，返回所有航班信息
            $flights = getDestinationsFromCity($flightData, $version, $departure, $weekdays);
            $response['flightsFromCity'] = $flights;
        } elseif (!empty($destination)) {
            // 只选择了目的地，返回所有航班信息
            $flights = getOriginsToCity($flightData, $version, $destination, $weekdays);
            $response['flightsToCity'] = $flights;
        }
        
        echo json_encode($response, JSON_UNESCAPED_UNICODE);
        break;
        
    default:
        echo json_encode(['error' => 'Invalid action'], JSON_UNESCAPED_UNICODE);
        break;
}
?>